package com.mogu_soup.util;

import com.mogu_soup.entity.Bullet;

import java.util.Vector;

/**
 * Version: 2.1
 * Author: TangJun
 * Date: 2024-08-02
 * Note:子弹对象池，避免重复创建和销毁子弹对象
 */
public class BulletsPool {
    private static final int DEFAULT_SIZE = 100;//默认子弹池大小
    private static final int MAX_SIZE = 500;//
    private static Vector<Bullet> pool;//子弹池
    //用静态代码块初始化，在类加载时就创建子弹对象
    static {
        pool = new Vector<Bullet>(DEFAULT_SIZE);
        for (int i = 0; i < DEFAULT_SIZE; i++) {
            pool.add(new Bullet(0,0,0,0));
        }
    }

    //获取子弹池中对象
    public static synchronized Bullet removeBullet() {
        return pool.isEmpty() ? new Bullet(0,0,0,0) : pool.remove(0);
    }

    //归还子弹池中对象
    public static synchronized void addBullet(Bullet bullet) {
        if (pool.size() < MAX_SIZE) {
            pool.add(bullet);
        }
    }
}
